package net.oschina.app.base;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

/**
 * 全局类：封装屏幕宽高获取，主线程运行，toast
 */
public class Global {

    // 屏幕参数
    public static int mScreenWidth;
    public static int mScreenHeight;
    public static float mDensity;

    public static Context mContext;

    public static void init(Context context) {
        mContext = context;

        DisplayMetrics dm = mContext.getResources().getDisplayMetrics();
        mScreenWidth =  dm.widthPixels;
        mScreenHeight =  dm.heightPixels;
        mDensity = dm.density;
    }

    /** dp转px */
    public static int dp2px(int dp) {
        return (int) (dp * mDensity + 0.5f);
    }

    public static Handler mHandler = new Handler(Looper.getMainLooper());

    /** 当前是否是在主线程 */
    public static boolean isMainThread() {
        return Looper.myLooper() == Looper.getMainLooper();
    }

    /** 主线程运行 */
    public static void runOnUIThread(Runnable runnable) {
        if (isMainThread()) {  // 当前为主线程
            runnable.run();
        } else { // 子线程
            mHandler.post(runnable);
        }
    }

    private static Toast mToast;

    /**
     * showToast,可以在子线程调用
     *
     * @param msg
     */
    public static void showToast(final String msg) {
        runOnUIThread(new Runnable() {
            @Override
            public void run() {
                if (mToast == null) {
                    mToast = Toast.makeText(mContext, msg, Toast.LENGTH_SHORT);
                }
                mToast.setText(msg);
                mToast.show();
            }
        });
    }

    public static View inflate(int layoutRes, ViewGroup parent) {
        return LayoutInflater.from(mContext).inflate(layoutRes, parent, false);
    }
}















